package com.example.saveword.dao;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.example.saveword.model.User;
import com.example.saveword.model.Word;
import com.example.saveword.model.WordRecord;
import com.example.saveword.utils.JsonUtils;
import com.example.saveword.utils.SPUtils;
import com.example.saveword.utils.TimeUtils;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;

@SuppressLint("Range")
public class WordRecordDao {
    private DBOpenHelper helper;
    private SQLiteDatabase db;
    private Context context;
    private WordDao wordDao;
    User user;
    public WordRecordDao(Context context){
        this.context=context;
        wordDao = new WordDao(context);
        user = (User) JsonUtils.jsonToObject((String) SPUtils.get(context, "User", ""), User.class);
    }
    //添加
    public void insert(WordRecord wordRecord)
    {
        helper=new DBOpenHelper(context);
        db=helper.getReadableDatabase();
        ContentValues values=new ContentValues();
        values.put("wordId",wordRecord.getWordId());
        values.put("level",wordRecord.getLevel());
        values.put("isFlag",wordRecord.getIsFlag());
        values.put("isOk",wordRecord.getIsOk());
        values.put("timeFirst",wordRecord.getTimeFirst());
        values.put("timeReview",wordRecord.getTimeReview());
        values.put("correct",wordRecord.getCorrect());
        values.put("user_id",wordRecord.getUser_id());
        db.insert("tb_wordRecord", null, values);
        db.close();
        helper.close();
    }
    //查询对应用户对应词书的单词记录
    public Set<WordRecord> findNowRecordList(String wordType)
    {
        Integer userId = user.get_id();
        helper=new DBOpenHelper(context);
        db=helper.getReadableDatabase();
        String sql="select * from tb_wordrecord where user_id = ?";
        Cursor cursor=db.rawQuery(sql,new String[]{String.valueOf(userId)});
        Set<WordRecord> res = new HashSet<>();
        while (cursor.moveToNext()) {
            Integer id = cursor.getInt(cursor.getColumnIndex("_id"));
            Integer wordId = cursor.getInt(cursor.getColumnIndex("wordId"));
            Integer level = cursor.getInt(cursor.getColumnIndex("level"));
            Integer isFlag = cursor.getInt(cursor.getColumnIndex("isFlag"));
            Integer isOk = cursor.getInt(cursor.getColumnIndex("isOk"));
            Long timeFirst = cursor.getLong(cursor.getColumnIndex("timeFirst"));
            Long timeReview = cursor.getLong(cursor.getColumnIndex("timeReview"));
            Integer Correct = cursor.getInt(cursor.getColumnIndex("Correct"));
            Integer user_id = cursor.getInt(cursor.getColumnIndex("user_id"));
            WordRecord wordRecord = new WordRecord(id, wordId, level, isFlag, isOk, timeFirst, timeReview, Correct, user_id);
            if(wordType.equals(wordDao.find(wordId).getWordType())) {
                res.add(wordRecord);
            }
        }
        cursor.close();
        db.close();
        helper.close();
        return res;
    }
    //查询对应用户对应词书的单词记录
    public Set<WordRecord> findNowRecordList()
    {
        Integer userId = user.get_id();
        helper=new DBOpenHelper(context);
        db=helper.getReadableDatabase();
        String wordType = user.getWordType();
        String sql="select * from tb_wordrecord where user_id = ? order by wordId";
        Cursor cursor=db.rawQuery(sql,new String[]{String.valueOf(userId)});
        Set<WordRecord> res = new HashSet<>();
        while (cursor.moveToNext()) {
            Integer id = cursor.getInt(cursor.getColumnIndex("_id"));
            Integer wordId = cursor.getInt(cursor.getColumnIndex("wordId"));
            Integer level = cursor.getInt(cursor.getColumnIndex("level"));
            Integer isFlag = cursor.getInt(cursor.getColumnIndex("isFlag"));
            Integer isOk = cursor.getInt(cursor.getColumnIndex("isOk"));
            Long timeFirst = cursor.getLong(cursor.getColumnIndex("timeFirst"));
            Long timeReview = cursor.getLong(cursor.getColumnIndex("timeReview"));
            Integer Correct = cursor.getInt(cursor.getColumnIndex("Correct"));
            Integer user_id = cursor.getInt(cursor.getColumnIndex("user_id"));
            WordRecord wordRecord = new WordRecord(id, wordId, level, isFlag, isOk, timeFirst, timeReview, Correct, user_id);
            if(wordType.equals(wordDao.find(wordId).getWordType())) {
                res.add(wordRecord);
            }
        }
        cursor.close();
        db.close();
        helper.close();
        return res;
    }
    // 返回今日需要复习的单词
    public List<Word> findNeedReview()
    {
        long now1 = TimeUtils.getNowTime();
        List<Word> ans = new ArrayList<>();
        Set<WordRecord> res;
        res = findNowRecordList();
        for(WordRecord i : res)
        {
            if(TimeUtils.isSameDay(i.getTimeFirst(), TimeUtils.getNowTime(), TimeZone.getDefault())) continue;
            if(i.getIsOk() == 0 && i.getTimeReview() <= TimeUtils.getNowTime())
            {
                ans.add(wordDao.find(i.getWordId()));
            }
        }
        return ans;
    }
    // 返回当前词书已经收藏的map
    public List<WordRecord> findIsFlag()
    {
        List<WordRecord> ans = new ArrayList<>();
        Set<WordRecord> res;
        res = findNowRecordList();
        for(WordRecord i : res)
        {
            if(i.getIsFlag() == 1)
                ans.add(i);
        }
        return ans;
    }
    // 判断是否存在记录
    public boolean isRecord(Word word)
    {
        helper=new DBOpenHelper(context);
        db=helper.getReadableDatabase();
        String sql="select * from tb_wordrecord where wordId = ?";
        Cursor cursor=db.rawQuery(sql,new String[]{String.valueOf(word.get_id())});
        return cursor.moveToNext();
    }
    public WordRecord AddOrGet(Word word)
    {
        WordRecord wordRecord = new WordRecord();
        if(isRecord(word))
        {
            wordRecord = getRecord(word);
        }
        else
        {
            wordRecord.setWordId(word.get_id());
            wordRecord.setLevel(1);
            wordRecord.setTimeFirst(TimeUtils.getNowTime());
            wordRecord.setTimeReview(TimeUtils.getNextReviewTime(10));
            wordRecord.setCorrect(0);
            wordRecord.setIsFlag(0);
            wordRecord.setUser_id(user.get_id());
            wordRecord.setIsOk(0);
            insert(wordRecord);
        }
        return wordRecord;
    }
    // 判断是否收藏
    public boolean isFlag(Word word)
    {
        List<WordRecord> res;
        res = findIsFlag();
        for(WordRecord i : res)
        {
            if(i.getWordId() == word.get_id())
                return true;
        }
        return false;
    }
    // 返回单词对应的记录
    public WordRecord getRecord(Word word)
    {
        helper=new DBOpenHelper(context);
        db=helper.getReadableDatabase();
        String sql="select * from tb_wordrecord where wordId = ?";
        Cursor cursor=db.rawQuery(sql,new String[]{String.valueOf(word.get_id())});
        if(cursor.moveToNext())
        {
            Integer id = cursor.getInt(cursor.getColumnIndex("_id"));
            Integer wordId = cursor.getInt(cursor.getColumnIndex("wordId"));
            Integer level = cursor.getInt(cursor.getColumnIndex("level"));
            Integer isFlag = cursor.getInt(cursor.getColumnIndex("isFlag"));
            Integer isOk = cursor.getInt(cursor.getColumnIndex("isOk"));
            Long timeFirst = cursor.getLong(cursor.getColumnIndex("timeFirst"));
            Long timeReview = cursor.getLong(cursor.getColumnIndex("timeReview"));
            Integer Correct = cursor.getInt(cursor.getColumnIndex("Correct"));
            Integer user_id = cursor.getInt(cursor.getColumnIndex("user_id"));
            WordRecord wordRecord = new WordRecord(id, wordId, level, isFlag, isOk, timeFirst, timeReview, Correct, user_id);
            return wordRecord;
        }
        return null;
    }
    // 点击收藏
    public void setFlag(Word word)
    {
        if(isFlag(word))
        {
            WordRecord wordRecord = getRecord(word);
            wordRecord.setIsFlag(0);
            update(wordRecord);
        }
        else
        {
            WordRecord wordRecord = getRecord(word);
            wordRecord.setIsFlag(1);
            update(wordRecord);
        }
    }
    //更新状态
    public void update(WordRecord wordRecord)  {
        helper=new DBOpenHelper(context);
        db=helper.getReadableDatabase();
        ContentValues values=new ContentValues();
        Integer userid = wordRecord.getUser_id();
        Integer id = wordRecord.get_id();
        values.put("wordId",wordRecord.getWordId());
        values.put("level",wordRecord.getLevel());
        values.put("isFlag",wordRecord.getIsFlag());
        values.put("isOk",wordRecord.getIsOk());
        values.put("timeFirst",wordRecord.getTimeFirst());
        values.put("timeReview",wordRecord.getTimeReview());
        values.put("Correct",wordRecord.getCorrect());
        db.update("tb_wordRecord",values,"_id=? and user_id = ?",new String[]{String.valueOf(id), String.valueOf(userid)});
        //关闭数据库
        db.close();
        helper.close();
    }

    // 返回对应用户所有的学习单词量
    public int getAllStudyWordNumById(String id) {
        helper = new DBOpenHelper(context);
        db = helper.getReadableDatabase();
        String sql = "select sum(newNum) from tb_studyrecord where user_id = ?";
        Cursor cursor = db.rawQuery(sql, new String[]{id});
        int sum = 0;
        if(cursor.moveToNext()) {
            sum = cursor.getInt(cursor.getColumnIndex("sum(newNum)"));
        }
        cursor.close();
        db.close();
        helper.close();
        return sum;
    }

    // 返回用户坚持打卡的天数
    public int getKeepTimeById(String id) {
        helper = new DBOpenHelper(context);
        db = helper.getReadableDatabase();
        String sql = "select count(*) from tb_studyrecord where user_id = ? and learnTime >= 20";
        Cursor cursor = db.rawQuery(sql, new String[]{id});
        int sum = 0;
        if(cursor.moveToNext()) {
            sum = cursor.getInt(cursor.getColumnIndex("count(*)"));
        }
        cursor.close();
        db.close();
        helper.close();
        return sum;
    }

    // 根据 id 和日期获取用户近七天每日学习时长
    public int getDAilyLearningTime(String id, String time) {
        helper = new DBOpenHelper(context);
        db = helper.getReadableDatabase();
        String sql = "select learnTime from tb_studyrecord where user_id = ? and date = ?";
        Cursor cursor = db.rawQuery(sql, new String[]{id, time});
        int num = 0;
        if(cursor.moveToNext()) {
            num = cursor.getInt(cursor.getColumnIndex("learnTime"));
        }
        cursor.close();
        db.close();
        helper.close();
        return num;
    }
}
